package 字符串.反转字符串中的单词;

import java.util.*;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/17 11:45
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String str = "a good   example";
        System.out.println(reverseWords(str));
        System.out.println(test2(str));
    }

    //采用单调栈+双指针的原理
    public static String reverseWords(String s) {
        Stack<String> stack = new Stack<>();
        //双指针
        int start = 0;
        int end = 0;
        //去除首尾的空格
        s = s.trim();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' '){
                end = i;
                //截取这部分单词
                String word = s.substring(start, end);
                //入栈
                stack.push(word);
                start = i + 1;
                while (s.charAt(start) == ' '){
                    start++;
                    i = start;
                }
            }
        }
       stack.push(s.substring(start,s.length()));
        //出栈
        StringBuilder sb = new StringBuilder();
        while (stack.size() != 0){
            if (stack.size() > 1){
                sb.append(stack.pop());
                sb.append(" ");
            }else {
                sb.append(stack.pop());
            }

        }
        return String.valueOf(sb);
    }

    //单个指针就可以，没必要用end
    public static String test2(String s) {
        s = s.trim();
        Stack<String> stack = new Stack<>();
        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                String tmp = s.substring(start, i);
                stack.push(tmp);
                while (s.charAt(i) == ' ') {
                    i++;
                }
                start = i;
            }
        }
        stack.push(s.substring(start));
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
            if (stack.size() > 0){
                sb.append(" ");
            }
        }
        return sb.toString();
    }


    /**
     * 使用 split 将字符串按空格分割成字符串数组；
     * 使用 reverse 将字符串数组进行反转；
     * 使用 join 方法将字符串数组拼成一个字符串。
     * @param s
     * @return
     */
    //使用语言特性，也就是使用java的API
    public static String reverseWords2(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }



}
